package com.my.blog.website.controller.admin;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import com.my.blog.website.config.QiniuUploadConfig;
import com.my.blog.website.dto.Types;
import com.my.blog.website.exception.TipException;
import com.my.blog.website.modal.Bo.QiniuResponse;
import com.my.blog.website.modal.Bo.RestResponseBo;
import com.my.blog.website.modal.Vo.*;
import com.my.blog.website.service.ICarouselService;
import com.my.blog.website.service.IContentService;
import com.my.blog.website.service.UploadService;
import com.my.blog.website.utils.FileUtils;
import com.my.blog.website.utils.UUID;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * @Description:轮播控制器
 * @Author 郭以华
 * @date 2019/10/15 - 18:07
 * @Version: 1.0
 */
@Controller
@RequestMapping("/admin/carousel")
@Transactional(rollbackFor = TipException.class)
public class CarouselController {
    private static final Logger LOGGER = LoggerFactory.getLogger(CarouselController.class);
    @Value("${cnbs.uploadCarouselWindows}")
    private String uploadCarouselWindows;

    @Value("${cnbs.uploadCarouselLinux}")
    private String uploadCarouselLinux;
    @Autowired
    private ICarouselService carouselService;

    @Resource
    private IContentService contentService;

    @Resource
    private UploadService uploadService;

    @Autowired
    private QiniuUploadConfig config;

    /**
     * 轮播列表
     *
     * @param page
     * @param limit
     * @param request
     * @return
     */
    @GetMapping(value = "")
    public String index(@RequestParam(value = "page", defaultValue = "1") int page,
                        @RequestParam(value = "limit", defaultValue = "10") int limit, HttpServletRequest request) {
        CarouselVoExample carouselVoExample = new CarouselVoExample();
        carouselVoExample.setOrderByClause("id asc");
        PageInfo<CarouselVo> carouselVoPageInfo = carouselService.getCarouselsWithpage(carouselVoExample, page, limit);
        request.setAttribute("carousels", carouselVoPageInfo);
        return "admin/carousel_list";
    }

    /**
     * 轮播状态控制
     *
     * @param id
     * @param flag
     * @return
     */
    @PostMapping(value = "/changeCarouselState")
    @ResponseBody
    public String changeCarouselState(@RequestParam(value = "id") int id,
                                      @RequestParam(value = "flag") String flag) {
        String cflag = flag.equals("1") ? "y" : "n";
        //查询一共有多少个被启用
        String result = carouselService.getCarouselStatusY();
        if (cflag == "n") {
            //根据轮播id修改状态
            carouselService.updateCarouselStatus(id, cflag);
            return "yes";
        } else if (cflag == "y" && result == "yes") {
            carouselService.updateCarouselStatus(id, cflag);
            return result;
        }
        return result;
    }


    @PostMapping(value = "/delete")
    @ResponseBody
    public R deleteCarousel(@RequestParam(value = "cid") int cid) {
        if (String.valueOf(cid).equals("")) {
            return R.error("id不为空");
        }
        carouselService.deleteCarouselById(cid);
        return R.ok();
    }

    /**
     * 删除文件
     *
     * @return
     */
   /* @DeleteMapping("/file")
    public R delete(@RequestParam(value = "cid") int cid) {
        if (String.valueOf(cid).equals("")) {
            return R.error("id不为空");
        }
        try {
            uploadService.delete(name);
            response = ApiResponse.ofMessage("删除成功");
        } catch (QiniuException e) {
            e.printStackTrace();
            throw new JsonException(Status.UNKNOWN_ERROR);
        }
        return response;
    }*/
    @GetMapping(value = "addCarousel")
    public String addCarousel(HttpServletRequest request) {
        return "admin/carousel_edit";
    }

    /**
     * 轮播图片上传>>上传到服务器,上指定目录
     *
     * @param file
     * @return
     */
    @PostMapping(value = "upload_server")
    @ResponseBody
    public R upload_server(@RequestParam(value = "img", required = true) MultipartFile file) {
        //将图片上传到服务器
        if (file.isEmpty()) {
            return R.error(HttpStatus.SC_NOT_FOUND, "项目图片不能为空");
        }
        //获取原文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        //图片名称为uuid+图片后缀防止冲突
        String fileName = UUID.UU32() + "." + suffix;
        String os = System.getProperty("os.name");
        //文件保存路径
        String filePath = "";
        if (os.toLowerCase().startsWith("win")) {
            //windows下的路径
            filePath = uploadCarouselWindows;
        } else {
            //linux下的路径
            filePath = uploadCarouselLinux;
        }
        try {
            Boolean uploadFileFlag = FileUtils.uploadFile(file.getBytes(), filePath, fileName);
            if (uploadFileFlag == false) {
                //上传图片失败
                return R.error(HttpStatus.SC_BAD_REQUEST, "上传图片失败");
            }
            //上传成功后，返回相对路径，该路径在Windows和linux都做了映射
            String fullImgpath = "/carouselPic/" + fileName;
            return R.ok("上传图片成功").put("url", fullImgpath);
        } catch (Exception e) {
            e.printStackTrace();
            //上传图片失败
            return R.error(HttpStatus.SC_BAD_REQUEST, "上传图片失败");
        }
    }

    /**
     * 轮播图片上传>>上传到七牛云
     *
     * @param file
     * @return
     */
    @PostMapping(value = "upload_qiniu")
    @ResponseBody
    public R upload_qiniu(@RequestParam(value = "img", required = true) MultipartFile file)
            throws IOException {
        if (file.isEmpty()) {
            return R.error(HttpStatus.SC_NOT_FOUND, "项目图片不能为空");
        }
        try {
            Response fileResponse = uploadService.upload(file);
            QiniuResponse info = fileResponse.jsonToObject(QiniuResponse.class);
            //修改七牛云返回的url没有http://
            return R.ok("上传图片成功").put("url", "http://" + info.getUrl());
        } catch (IOException e) {
            e.printStackTrace();
            //上传图片失败
            return R.error(HttpStatus.SC_BAD_REQUEST, "上传图片失败");
        }
    }

    /**
     * 发布轮播
     *
     * @param carouselVo
     * @param request
     * @return
     */
    @PostMapping(value = "/publish")
    @ResponseBody
    @Transactional(rollbackFor = TipException.class)
    public R publishCarousel(CarouselVo carouselVo, HttpServletRequest request) {
        try {
            carouselService.publish(carouselVo);
        } catch (Exception e) {
            String msg = "轮播发布失败";
            if (e instanceof TipException) {
                msg = e.getMessage();
            } else {
                LOGGER.error(msg, e);
            }
            return R.error(msg);
        }
        return R.ok();
    }

    /**
     * 轮播图设置
     *
     * @return
     */
    @GetMapping(value = "/setting")
    public String carouselsetting(HttpServletRequest request) {
        PageInfo<ContentVo> articles = contentService.getContents(1, 15);
        request.setAttribute("articles", articles);
        //轮播列表
        List<CarouselVo> carouselVoList = carouselService.getCarouselList();
        request.setAttribute("carousels", carouselVoList);
        return "admin/carousel_setting";
    }


}
